package com.haidao.admin.component.service.impl;

import com.haidao.admin.component.constants.JwtConstant;
import com.haidao.admin.component.dao.UserDao;
import com.haidao.admin.component.params.LoginParam;
import com.haidao.admin.component.service.UserService;
import com.haidao.admin.component.entity.User;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Override
    public User login(LoginParam param) {
        User user = userDao.findUserByUserName(param.getUserName());
        return user;
    }

    @Override
    public String genToken(User user) throws JOSEException {
        MACSigner macSigner = new MACSigner(JwtConstant.SECRET);
        JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.HS256);

        JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                .subject(user.getUserName())
                .expirationTime(new Date(System.currentTimeMillis()))
                .claim("userName", user.getUserName())
                .claim("phone", user.getPhone())
                .build();

        SignedJWT signedJWT = new SignedJWT(jwsHeader, claimsSet);
        signedJWT.sign(macSigner);
        return signedJWT.serialize();
    }

    @Override
    public User detail(String subject) {
        return userDao.findUserByUserName(subject);
    }

}